﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gt.UserInfo.ApplicationServices;
using gt.UserInfo.DomainModels.ApiRequests;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using gt.dotnetcore.webapi.extensions;
using Microsoft.AspNetCore.Http;

namespace gt.UserInfo.Controllers
{
    [ApiVersion("1.0")]
    [ApiVersion("2.0")]
    //多路由支持
    [Route("api/v{version:apiVersion}/[controller]")]
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ApiControllerBase
    {
        private readonly IUserAppService _userService;
        private readonly IHttpContextAccessor _contextAccessor;

        public UserController(IUserAppService userService,
            IHttpContextAccessor contextAccessor)
        {
            _userService = userService;
            _contextAccessor = contextAccessor;
        }
        [Route("register")]
        [HttpPost]
        public async Task<IActionResult> Register(RegisterUserRequest request)
        {
            if (string.IsNullOrEmpty(request.Name)
                || string.IsNullOrEmpty(request.ShowName)
                || string.IsNullOrEmpty(request.Password)
                || string.IsNullOrEmpty(request.Phone))
                return BadRequest();

            var userId = await _userService.RegisterAsync(request);

            return Success(userId);
        }

        [Route("headclaims")]
        [HttpGet]
        public async Task<IActionResult> HeadClaims()
        {
            //note:http head 不支持中文字符，所以showname和introduce不能获取
            var claimTypes = new List<string> { "name", "showname", "userId", "introduce", "client_id" };
            var claimHeads = Request.Headers.Where(x => claimTypes.Contains(x.Key));
            //var user = _contextAccessor.HttpContext.User;
            if (claimHeads == null) return Success();
            var dic = new Dictionary<string, string>();
            foreach (var ch in claimHeads)
            {
                dic.Add(ch.Key, ch.Value.ToString());
            }

            return await Task.FromResult(Success(dic));
        }

        [Route("headclaims")]
        [HttpGet, MapToApiVersion("2.0")]
        public async Task<IActionResult> HeadClaimsv2()
        {
            var claimTypes = new List<string> { "name", "showname", "introduce", };
            var claimHeads = Request.Headers.Where(x => claimTypes.Contains(x.Key));
            var user = Request.HttpContext.User;
            if (claimHeads == null) return Success();
            var dic = new Dictionary<string, string>();
            foreach (var ch in claimHeads)
            {
                dic.Add(ch.Key, ch.Value.ToString());
            }

            return await Task.FromResult(Success(dic));
        }

        [Route("ping")]
        [HttpGet]
        public async Task<IActionResult> Ping()
        {
            return await Task.FromResult(Success("ok"));
        }
    }
}
